package com.cps116.friendstracker;


import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;



import com.easy.facebook.android.apicall.FQL;
import com.easy.facebook.android.error.EasyFacebookError;


import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ProfileActivity extends BaseActivity {

	public static final String TAG = ProfileActivity.class.getSimpleName();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profileactivity_layout);

		//setup the data adapter for the item lists and display the update option
		Spinner timeUpdateOptionSpinner = (Spinner) findViewById(R.id.location_update_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.profile_update_option_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		timeUpdateOptionSpinner.setAdapter(adapter);
		timeUpdateOptionSpinner.setOnItemSelectedListener(new UpdateOptionListener());

		//register the buttonlistener
		Button setupButton = (Button) findViewById(R.id.profile_view_preference_button);
		setupButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				//set up the prefActivity
				startActivity(new Intent(v.getContext(), PrefActivity.class)); 
			}
		});

		
		//pull the image and username from FQL
		FQL facebookFQL = ((FriendsTrackerApplication) getApplication()).getFacebookFQL();
		new ProfileFacebookDataPuller(this).execute(facebookFQL);
		
		//here we simply need to get the user_id from FQL and the user the user_id as the key 
		//for the Austin's database...
		new ProfileDatabaseLocationDataPuller(this).execute(facebookFQL);

		//TODO setup broadcast listener for location updates...[dynamic list update]
		

	}  


	@Override
	protected void onPause() {
		super.onPause();
		
		//turn off the location service listener for update
		//set the user service here!
	}

	@Override
	protected void onResume() {
		super.onResume();
		//turn off the location service listern for update
	}

	
	
	/**
	 * Update the Update Option spinner and reset the GPS  
	 *
	 */

	private class UpdateOptionListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int index,
				long arg3) {

			String user_time_choice = parent.getItemAtPosition(index).toString();
			
			//display the message that you have updated 
			Toast.makeText(parent.getContext(), String.format("Current update time: %s",
					user_time_choice), Toast.LENGTH_LONG).show();

			//convert the user_time_choice to string
			float new_update_time = timeOptionConverter(user_time_choice);
			((FriendsTrackerApplication) getApplication()).setUserLocationUpdateServiceInterval(new_update_time);
			
			//terminate all existing user location update thread on the service that are currently running
			
		}

		public void onNothingSelected(AdapterView<?> view) {
			//do not change anything
		}
		
		public float timeOptionConverter(String option)
		{
			//TODO: overwrite this timeOptionConverter
			//convert from user spinner choice to floats in seconds
			return 0;
		}
	}




	/**
	 * Fetch the previous five locations that the user 
	 * You might want to do threading here..because you need to parse the user_id from facebok
	 * before you can secure a connection here!
	 */
	private class ProfileDatabaseLocationDataPuller extends AsyncTask<FQL, String, String>{

		private ProfileActivity profileActivity;

		public ProfileDatabaseLocationDataPuller(ProfileActivity activity)
		{
			profileActivity = activity;
		}

		@Override
		protected String doInBackground(FQL... fql) {
			//TODO: fetch ther user_id from the FQL
			//establish a database connection 
			//if the user does not have a id..make it.
			//use list and listadapters to pull in large amount of data 
			//fetch the user's preference for update interval
			//set the user preference that on the spinner
			//
			//
			//if user_id not in database...do default setup
			//
			
			
			return "testing";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);



		}
	}

	/**
	 * Pull the facebook icon image, username and facebook id from
	 * FQL
	 * 
	 */
	private class ProfileFacebookDataPuller extends AsyncTask<FQL, String, String> {

		private Activity profileActivity;

		public ProfileFacebookDataPuller(ProfileActivity profileActivity) {
			this.profileActivity = profileActivity;
		}

		@Override
		protected String doInBackground(FQL... fql) {

			FQL facebookdb = fql[0];
			try {
				//obtain an xml document with embedded references
				//yes it works! && be sure to trim off to get only the xml parts 
				String result_xml = facebookdb.fqlQuery("SELECT uid, name, pic_square FROM user WHERE uid = me()");
												
				
//				SAXBuilder builder = new SAXBuilder();
//				Document document = builder.build(new StringReader(result_xml));
//				
//				Element root = document.getRootElement();
//				
//				String user_name = xml_request_root.getChild("name").getValue();
//
//				Log.d("testing", user_name);
//
//				String pic_url = xml_request_root.getChild("pic_square").getValue();
//
//				Log.d("testing", pic_url);

				//set up the username to be displayed
//				TextView user_field = (TextView) profileActivity.findViewById(R.id.profile_activity_username_textview);
//				user_field.setText(user_name);

				//set up the image to be displayed			

				return "ProfileFacebookDataPuller succeeded";

			} catch (Exception e) {

				return "ProfileFacebookDataPuller failed";				 
			}
		}


		@Override
		protected void onPostExecute(String result) {

			Log.d(TAG, result);
			super.onPostExecute(result);
		}

	}








}